<template>
  <div :class="['tr-select-big', 'no-outline', styles.module]" v-bind="$attrs" tabIndex="-1">
    <LabelPrefixWraper :class="['tr-select', 'no-outline', styles.module]" v-show="mappingProps.visible"
      :label="mappingProps.label" :required="mappingProps.required" :hideLabel="mappingProps.hideLabel"
      :labelPosition="mappingProps.labelPosition" :helpConf="mappingProps.helpConf"
      :helpTooltip="mappingProps.helpTooltip" :helpPlacement="mappingProps.helpPlacement"
      :helpMore="mappingProps.helpMore" :helpMorePopup="mappingProps.helpMorePopup"
      :helpMoreLink="mappingProps.helpMoreLink" :helpMoreLinkHrefStatic="mappingProps.helpMoreLinkHrefStatic"
      :helpMoreLinkHrefExp="mappingProps.helpMoreLinkHrefExp" :readonly="mappingProps.readonly">
      <Component ref="refComponent" :class="['tr-select-small', 'no-outline', styles.module]"
        v-bind="{ ...attrs_, ...mappingProps }" v-model:modelValue="mappingProps.modelValue" :label="undefined"
        @clear="clear" :dense="true" :options-dense="true" :borderless="mappingProps.borderless" :emitValue="true"
        :mapOptions="true" v-model:displayDataSource="proxyModelValue" :useInput="mappingProps.useInput"
        :hideSelected="mappingProps.useInput" :fillInput="mappingProps.useInput"
        :dropdown-icon="mappingProps.dropdownIcon" inputdebounce="0" :options="mappingProps.itemsDataSourceType === ''
            ? options
            : mappingProps.itemsDataSourceType === 'static'
              ? staticItems
              : listDataSource
          " @filter="filterFn" @popup-show="popupShow">
        <template v-slot:no-option>
          <t-item>
            <t-item-section class="text-grey">{{ $q.lang.select?.noData || '无数据' }}
            </t-item-section>
          </t-item>
        </template>
        <!-- <template v-for="(v, k, a) in $slots" v-slot:[k]="slotProps">
          <slot :name="k" v-bind="slotProps" />
        </template> -->
        <template v-for="(v, k, a) in $slots" #[k]="slotProps">
          <slot :name="k" v-bind="{ ...slotProps }" />
        </template>
        <template v-if="mappingProps.readonly && mappingProps.enableMask && initMask() && sysHasMaskAuth()" v-slot:append>
          <span class="fas-label-mask custom">
            <i :class="!isMasked
                ? 'dx-icon fas icon-t-mask-open'
                : 'dx-icon fas icon-t-mask-close'
              " style="font-size: 14px" @click="maskIconClick"></i>
          </span>
        </template>
      </Component>
    </LabelPrefixWraper>
  </div>
</template>

<script>
import { useQuasar } from '@teld/q-components';
import Component from '@teld/q-components/Select';
import useMappingProps from 't/common/hooks/useMappingProps';
import { commonProps, fixNameSpace } from 't/common/utils';
import { computed, defineComponent, ref, watch, onMounted } from 'vue';
import LabelPrefixWraper from '../label-prefix-wraper';
import styles from './index.module.scss';
import './index.scss';
import { useI18n } from 'vue-i18n';
import useMark, { sysHasMaskAuth } from 't/common/hooks/useMask';
export default defineComponent({
  name: fixNameSpace(Component.name),
  components: { Component, LabelPrefixWraper },
  props: {
    ...commonProps,
    ...Component.props,
    ...LabelPrefixWraper.props,
    placeholder: {
      type: String,
      default: '',
    },
    itemsDataSourceType: {
      type: String,
      default() {
        return '';
      },
    },
    borderless: {
      type: Boolean,
      default() {
        return true;
      },
    },
    lazyLoading: {
      type: Boolean,
      default() {
        return false;
      },
    },
    alwaysLoad: {
      type: Boolean,
      default() {
        return false;
      },
    },
    displayDataSource: String,
    options: Array,
    listDataSource: Array,
    staticItems: Array,
    displayField: String,
    valueField: String,
    dropdownIcon: {
      type: String,
      default() {
        // return 'fas dx-icon icon-t-down-outlined';
        return `${TComponents?.IconList?.common ?? 'fas dx-icon'} ${TComponents?.IconList?.arrowDown ?? 'icon-t-arrow-down'}`;
      },
    },
    opening: Function,
    enableMask: {
      type: Boolean,
      default() {
        return false;
      },
    },
    value_mask: String,
  },
  emits: [
    'change',
    'clear',
    'update:modelValue',
    'lazy-load',
    'update:displayDataSource',
  ],
  inheritAttrs: false,
  setup(props, { attrs, emit, expose, slots }) {
    const $q = useQuasar();
    // 添加一个新的响应式状态变量来跟踪是否是首次展开
    const { t } = useI18n({ useScope: 'global' });
    const isFirstOpen = ref(true);
    let attrs_ = { ...attrs };
    delete attrs_['data-uid'];
    delete attrs_['data-tag'];
    delete attrs_['class'];
    delete attrs_['style'];
    const refComponent = ref();
    const isMasked = ref(true);
    const IsMasked = computed(() => {
      return isMasked.value;
    });
    const [mappingProps, mappingExpose] = useMappingProps(props, {
      selectLabel: '',
      validate() {
        return refComponent.value.validate(...arguments);
      },
      resetValidation() {
        refComponent.value.resetValidation(...arguments);
      },
      search() {
        emit('lazy-load');
      },
      focus() {
        refComponent.value.focus(...arguments);
      },
      showMask: (val) => {
        if (!sysHasMaskAuth() || !props.enableMask) return
        isMasked.value = val
      },
      ShowMask: (val) => {
        if (!sysHasMaskAuth() || !props.enableMask) return
        isMasked.value = val
      },
      IsMasked,
      isMasked: IsMasked,
      showPopup: () => {
        refComponent.value.showPopup()
      },
      hidePopup: () => {
        refComponent.value.hidePopup()
      }
    });
    const { initMask, maskIconClick } = useMark(mappingProps, '', isMasked);
    expose(mappingExpose);
    function clear() {
      emit('clear');
    }
    let proxyModelValue = ref('');

    watch(
      () => [
        mappingProps.readonly,
        mappingProps.disabled,
        isMasked.value,
        mappingProps.modelValue,
        mappingProps.value_mask,
      ],
      () => {
        if (
          isMasked.value &&
          mappingProps.readonly &&
          mappingProps.enableMask
        ) {
          proxyModelValue.value = mappingProps.value_mask;
        } else {
          proxyModelValue.value = mappingProps.displayDataSource;
        }
      },
      {
        immediate: true,
      },
    );
    watch(
      () => proxyModelValue.value,
      () => {
        if (!isMasked.value || !mappingProps.readonly) {
          mappingProps.displayDataSource = proxyModelValue.value;
        }
      },
    );
    const dynamicList = (list, ismask) => {
      if (!(list instanceof Array)) return [];
      if (list.length == 0) {
        list = [];
      }
      return list.map(item => {
        let key = mappingProps.displayField
        if (ismask) {
          key = mappingProps.displayField + '_mask'
        }
        const obj = {
          label: item[key],
          value:mappingProps.multiple? item[mappingProps.valueField]+'':item[mappingProps.valueField],
        };
        return { ...item, ...obj };
      });
    };

    const filterValue = ref();

    const options = ref(mappingProps.options);
    const computedStaticItems = list => {
      if (list) {
        return list.map(item => {
          return { ...item, label: t(item.ValueInfo_label || '', item.label) ,value: mappingProps.multiple?(item.value+''):item.value };
        });
      } else {
        return [
          {
            label: mappingProps.displayDataSource,
            value: mappingProps.modelValue,
          },
        ];
      }
    };

    const staticItems = ref(computedStaticItems(mappingProps.staticItems));

    watch(
      () => mappingProps.staticItems,
      () => {
        staticItems.value = computedStaticItems(mappingProps.staticItems);
      },
      {
        immediate: true,
      },
    );
    const listDataSource = computed(() => {
      let list = dynamicList(mappingProps.listDataSource, mappingProps.readonly && mappingProps.enableMask && initMask() && isMasked.value).filter(v =>
        filterValue.value
          ? v.label.toString().toLowerCase().indexOf(filterValue.value) > -1
          : true,
      );
      if (list.length == 0 && mappingProps.lazyLoading == true) {
        let key = mappingProps.displayDataSource
        if (mappingProps.readonly && mappingProps.enableMask && initMask() && isMasked.value) {
          key = mappingProps.value_mask
        }
        let defaultList = [
          {
            label: key,
            value: mappingProps.modelValue,
          },
        ];
        return defaultList;
      }
      console.log(listDataSource.value, 'listDataSource');
      return list;
    });

    function filterFn(val, update, abort) {
      if (mappingProps.itemsDataSourceType === 'static') {
        update(() => {
          debugger;
          const needle = val.toString().toLowerCase();
          staticItems.value = computedStaticItems(
            mappingProps.staticItems,
          ).filter(v => v.label.toString().toLowerCase().indexOf(needle) > -1);
        });
      } else if (mappingProps.itemsDataSourceType === 'dynamic') {
        update(() => {
          filterValue.value = val.toString().toLowerCase();
        });
      } else {
        update(() => {
          const needle = val.toString().toLowerCase();
          options.value = mappingProps.options.filter(
            v => v.label.toString().toLowerCase().indexOf(needle) > -1,
          );
        });
      }
    }
    function popupShow() {
      let Data = {};
      mappingProps.opening && mappingProps.opening(Data);
      if (mappingProps.lazyLoading && isFirstOpen.value) {
        emit('lazy-load');
        isFirstOpen.value = false;
      } else if (mappingProps.lazyLoading && mappingProps.alwaysLoad) {
        emit('lazy-load');
      }
      if (Data.cancel) {
        refComponent.value.hidePopup();
      }
    }
    const watchListDataSourceLength = () => {
      watch(
        () => mappingProps.modelValue,
        (value, oldValue) => {
          emit('update:modelValue', mappingProps.modelValue);
          let options1 =
            mappingProps.itemsDataSourceType === ''
              ? options.value
              : mappingProps.itemsDataSourceType === 'static'
                ? staticItems.value
                : listDataSource.value;
          if (mappingProps.multiple) {
            if (Array.isArray(mappingProps.modelValue)&&JSON.stringify(mappingProps.modelValue) !== JSON.stringify(oldValue)) {
              mappingProps.modelValue.forEach(el =>  el+'')
              let selectLabelitemList = options1.filter(option => mappingProps.modelValue.some(el => el == option.value));
              if (selectLabelitemList && selectLabelitemList.length) {
                if (mappingProps.enableMask) {
                  let value_mask = selectLabelitemList.map(item => item[mappingProps.displayField + '_mask']).join(',');
                  emit('update:value_mask', value_mask)
                }
                emit('confirm', selectLabelitemList);
                let label = selectLabelitemList.map(item => item.value).join(',');
                mappingExpose.selectLabel = label;
                //if(mappingProps.displayDataSource){
                mappingProps.displayDataSource = label;
                emit('update:displayDataSource', mappingProps.displayDataSource);
                //}
                emit('change', value);
              }
            }
            return
          }else{

          }
          // nextTick(() => { emit('change', value)})

          let selectLabelitem = options1.find(option => option.value === value);
          if (selectLabelitem) {
            if (mappingProps.enableMask) {
              emit('update:value_mask', selectLabelitem[mappingProps.displayField + '_mask'])
            }
            emit('confirm', selectLabelitem);
            mappingExpose.selectLabel = selectLabelitem.label;
            //if(mappingProps.displayDataSource){
            mappingProps.displayDataSource = selectLabelitem.label;
            emit('update:displayDataSource', mappingProps.displayDataSource);
            //}
            emit('change', value);
          }
        },
      );
    };
    onMounted(() => {
      watchListDataSourceLength();
    });

    return {
      refComponent,
      attrs_,
      styles,
      mappingProps,
      clear,
      dynamicList,
      staticItems,
      listDataSource,
      isFirstOpen,
      filterFn,
      popupShow,
      computedStaticItems,
      initMask,
      maskIconClick,
      isMasked,
      proxyModelValue,
      sysHasMaskAuth
    };
  },
});
</script>

<style lang="scss" scoped></style>
